package com.liujit.standard.basis.admin.config.interceptor;

import com.alibaba.fastjson.JSON;
import com.liujit.standard.basis.admin.util.ApiUtil;
import com.liujit.standard.basis.core.domain.result.UserInfo;
import com.liujit.standard.basis.core.enums.ResultCode;
import com.liujit.standard.basis.core.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @description: 登录校验拦截器配置
 * @author: liujun
 * @create: 2021/3/24 6:39 下午
 **/
@Slf4j
public class LoginStateInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // 拦截处理代码
        UserInfo user = ApiUtil.getSysUser();
        if (user == null) {
            returnJson(response, Result.failure(ResultCode.USER_NOT_LOGGED_IN));
            return false;
        }
        return true;
    }

    private void returnJson(HttpServletResponse response, Result res) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(res));
        } catch (IOException e) {
            log.error("response error", e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}
